package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.JedisUtil;
import com.itheima.utils.QiNiuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Reference
    SetmealService setmealService;

    @Autowired
    JedisUtil jedisUtil;

    /**
     * 1、form表单提交数据的格式 （name=jack&age=18&address=shangshou） 后端用对象接收不需要加注解
     * 2、页面传的是json数据，后端使用map 或者 pojo时 需要加@RequestBody
     * 3、基本类型 & 数组 & MultipartFile 只要保持页面的参数名称和controller方法形参一致就不用加@RequestParam
     * 4、List 不管名字一不一样 必须加@RequestParam
     *
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile) {
        String originalFilename = imgFile.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String newFileName = UUID.randomUUID().toString() + originalFilename.substring(index);
        try {
            QiNiuUtil.upload(imgFile.getBytes(), newFileName);
            jedisUtil.sadd(RedisConstant.SETMEAL_PIC_RESOURCES,newFileName);
            return Result.success(MessageConstant.PIC_UPLOAD_SUCCESS, newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal) {
        setmealService.add(setmeal);
        jedisUtil.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        return Result.success(MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return setmealService.findPage(queryPageBean);
    }
}
